package com.whc.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whc.common.Cache;
import com.whc.common.exception.MessageException;
import com.whc.entity.Shell;
import com.whc.mapper.ShellMapper;
import com.whc.service.ShellService;
import com.whc.util.AssertUtil;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 *
 */
@Service
public class ShellServiceImpl extends ServiceImpl<ShellMapper, Shell>
        implements ShellService {
    Runtime runtime = Runtime.getRuntime();

    @Override
    public Object on() {
        Cache.sw = true;
        return true;
    }

    @Override
    public Object off() {
        Cache.sw = false;
        return true;
    }

    @Override
    public void stop() {
        System.exit(0);
    }

    @Override
    public boolean exec(String code) {
        Shell shell = lambdaQuery()
                .eq(Shell::getCode, code)
                .one();
        AssertUtil.isNull(shell, "脚本不存在");
        try {
            runtime.exec(new String[]{"sh", "-c", shell.getShell()});
        } catch (IOException e) {
            e.printStackTrace();
            throw MessageException.instance("执行失败");
        }
        return true;
    }
}




